﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using Kugar.ERPFramework.ClientBroker;
using Kugar.ERPFramework.Core.Entity;

namespace Kugar.ERPFramework.View.WinForm
{

    public partial class ModuleFormBase : Office2007Form, IModuleForm
    {
        protected IModuleFormControlRMSProvider _rmsControlProvider = null;
        private static IClientBroker  _broker = null;

        static ModuleFormBase()
        {
            ControlManagement = new ControlManagement();
        }

        public ModuleFormBase()
        {
            if (!this.FormRMSChecked())
            {
                throw new RMSFaildException();
            }

            InitializeComponent();
        }

        public ModuleFormBase(IModuleFormControlRMSProvider rmsControlProvider)
            : this()
        {
            if (rmsControlProvider==null)
            {
                rmsControlProvider=new ResourcesRMSProvider();
            }
            _rmsControlProvider = rmsControlProvider;
        }


        public override string Text
        {
            get
            {
                return base.Text;
            }
            set
            {
                base.Text = value;
            }
        }

        public static ControlManagement ControlManagement { set; get; }

        [Browsable(false)]
        public static IClientBroker ClientBroker
        {
            get { return _broker; }
            set { _broker = value; }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            ControlRMSChecked();
        }

        /// <summary>
        ///     当前窗体是否只读
        /// </summary>
        protected bool IsReadOnly { set; get; }

        protected virtual void ControlRMSChecked()
        {
            if (_rmsControlProvider == null)
            {
                return;
            }

            var rmsList = _rmsControlProvider.GetControlRMSList(this.GetType());

            if (rmsList == null || rmsList.Count <= 0)
            {
                return;
            }

            foreach (var item in rmsList)
            {
                if (string.IsNullOrWhiteSpace(item.Key))
                {
                    continue;
                }

                var ctrlLst = this.Controls.Find(item.Key, true);

                if (ctrlLst == null || ctrlLst.Length <= 0)
                {
                    continue;
                }

                //TODO:调用Broker判断是否有权限

                //TODO:如果没有则处理相应控件
                foreach (var control in ctrlLst)
                {
                    if (item.Value.WhenFaild == ControlRMSItem.ControlRMSFaildHandle.Hide)
                    {
                        ControlManagement.SetControlHide(control);
                    }
                    else
                    {
                        ControlManagement.SetControlDisabled(control);
                    }

                }
            }


        }

        protected virtual bool FormRMSChecked()
        {
            return true;
        }

        #region "显示提示框"

        protected virtual void ShowMessageBox(string msg)
        {
            ClientBroker.ShowMessage(msg);
        }

        protected virtual bool ShowMessageWithButton(string msg)
        {
            return ClientBroker.ShowMessageWithButton(msg);
        }

        protected virtual string ShowInputBox(string caption, string promo)
        {
            return ClientBroker.ShowInputBox(caption, promo);
        }

        #endregion

        protected void ShowBusing(Control parent, bool isShow, string processingText="")
        {
            this.circularProgress1.Visible = true;
            this.circularProgress1.BringToFront();
            parent.Enabled = !isShow;
            circularProgress1.IsRunning = isShow;
            lblBusyText.Text = processingText;
        }
    }

    public class ModuleRMSAttributeBase : Attribute
    {
        public ModuleRMSAttributeBase(params string[] rmsNames)
        {
            if (rmsNames == null || rmsNames.Length <= 0)
            {
                throw new Exception("请设定权限名称");
            }

            RMSList = rmsNames;
        }

        public string[] RMSList { get; private set; }
    }


    public class ModuleCreateRMSAttribute : ModuleRMSAttributeBase
    {
        public ModuleCreateRMSAttribute(params string[] rmsNames):base(rmsNames)
        {
        }
        
    }

    public class ModuleReadRMSAttribute : ModuleRMSAttributeBase
    {
        public ModuleReadRMSAttribute(params string[] rmsNames)
            : base(rmsNames)
        {
        }
    }


    public interface IModuleFormControlRMSProvider
    {
        Dictionary<string, ControlRMSItem> GetControlRMSList(Type type);
    }

    /// <summary>
    ///     从类型所属的dll的资源文件中读取控件权限控制列表
    /// </summary>
    public class ResourcesRMSProvider : IModuleFormControlRMSProvider
    {
        private static Dictionary<Type, Dictionary<string, ControlRMSItem>> _cacheRMSList = new Dictionary<Type, Dictionary<string, ControlRMSItem>>();

        #region Implementation of IModuleFormControlRMSProvider

        public Dictionary<string, ControlRMSItem> GetControlRMSList(Type type)
        {
            Dictionary<string, ControlRMSItem> ret = null;

            if (_cacheRMSList.TryGetValue(type,out  ret))
            {
                return ret;
            }

           

            var tempType = type;

            ret = new Dictionary<string, ControlRMSItem>();

            while (tempType!=typeof(object))
            {
                if (tempType==null)
                {
                    break;
                }

                var rm = new ResourceManager("RMSList", tempType.Assembly);

                var rmsStr = rm.GetString(tempType.FullName);

                var rmsList = Kugar.Core.ExtMethod.Serialization.SerializationExt.XMLToObject<ControlRMSItem[]>(rmsStr);

                if (rmsList != null && rmsList.Length > 0)
                {
                    foreach (var rmsItem in rmsList)
                    {
                        if (ret.ContainsKey(rmsItem.ControlName))
                        {
                            continue;
                        }
                        ret.Add(rmsItem.ControlName, rmsItem);
                    }
                }

                tempType = type.BaseType;

                if (tempType==typeof(object))
                {
                    break;
                }
            }

            _cacheRMSList.Add(type,ret);

            return ret;

        }

        #endregion
    }

    public class RMSFaildException : ApplicationException
    {
        public RMSFaildException() : base("当前用户无权限使用该功能") { }
    }

    public class ControlManagement
    {
        public void SetControlDisabled(Control ctrl)
        {
            if (ctrl is TextBox)
            {
                ((TextBox)ctrl).ReadOnly = true;
            }
            else
            {
                ctrl.Enabled = false;
            }
        }

        public void SetControlHide(Component ctrl)
        {
            if (ctrl is Control)
            {
                ((Control)ctrl).Visible = false;
            }
        }
    }

}
